var fs = require('fs');

var coords = [116.451209, 39.95462];

var verifylt = [
    [323.451, -1530.667],
    [788.287, -1529.711],
    [317.641, -918.044],
    [786.706, -918.986],
    [1251.368, -1529.914],
    [1722.18, -1528.969],
    [1253.894, -919.158],
    [1725.87, -918.607],
    [2191.612, -1527.831],
    [2196.268, -918.354],
    [322.056, -317.361],
    [791.727, -313.603],
    [319.055, 300.231],
    [790.777, 295.113],
    [1262.543, -313.393],
    [1729.428, -314.687],
    [1266.244, 298.979],
    [1724.782, 298.35],
    [317.94, 903.067],
    [794.23, 901.305],
    [1255.609, 907.947],
    [1732.04, 906.356],
    [2195.452, -313.292],
    [2196.549, 301.294],
    [2196.914, 904.994]
];

var verifyrb = [
    [799.599, -2143.836],
    [1267.86, -2145.408],
    [803.041, -1534.567],
    [1272.858, -1537.13],
    [1740.027, -2145.37],
    [2210.537, -2143.865],
    [1737.372, -1536.056],
    [2207.303, -1534.848],
    [2676.741, -2139.335],
    [2677.952, -1538.115],
    [795.41, -926.762],
    [1266.55, -924.76],
    [794.332, -321.184],
    [1262.325, -316.535],
    [1735.047, -924.807],
    [2198.331, -926.087],
    [1737.156, -319.836],
    [2206.861, -315.485],
    [791.843, 297.705],
    [1268.057, 291.512],
    [1737.585, 291.771],
    [2204.125, 288.039],
    [2672.512, -927.089],
    [2665.502, -318.371],
    [2685.042, 289.982]
]

function lnglat2xy(coords) {
    var x = -6378137 * coords[0] * (Math.PI / 180) * (512 / (6378137 * Math.PI) / 2);
    var y = -6378137 * Math.log(Math.tan((Math.PI * 0.25) + (0.5 * coords[1] * (Math.PI / 180)))) * (512 / (6378137 * Math.PI) / 2);
    return [x, y];
}

function xy2lnglat(xy) {
    var lng = -xy[0] / (6378137 * (Math.PI / 180) * (512 / (6378137 * Math.PI) / 2));
    var lat = 2 * (Math.atan(Math.exp(xy[1] / (512 / (6378137 * Math.PI) / 2 * (-6378137.0)))) - Math.PI / 4) / (Math.PI / 180);
    return [lng, lat];
}

function projectedUnitsPerMeter(latitude) {
    return Math.abs(512 * (1 / Math.cos(latitude*Math.PI/180))/40075000);
}

var xy = lnglat2xy(coords);
console.log(xy2lnglat(xy));
var pixelsPerMeter = projectedUnitsPerMeter(coords[1]);
console.log(pixelsPerMeter);

var xy1 = [];
for (var i = 0; i < verifylt.length; i++) {
    var subCoordslt = xy2lnglat([-verifylt[i][0] * pixelsPerMeter + xy[0], -verifylt[i][1] * pixelsPerMeter + xy[1]]);
    var subCoordsrb = xy2lnglat([-verifyrb[i][0] * pixelsPerMeter + xy[0], -verifyrb[i][1] * pixelsPerMeter + xy[1]]);

    xy1.push({
        "rbLat": subCoordsrb[1],
        "ltLng": subCoordslt[0],
        "ltLat": subCoordslt[1],
        "rbLng": subCoordsrb[0]
    })
}

console.log(xy1);

fs.writeFileSync('block-lnglat.json', JSON.stringify(xy1));